package com.vrv.framework.common.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页使用工具类
 * 
 * @author 曹保利
 * @version 1.0
 * 
 */
public class PageUtils {

	private PageUtils() {
	}

	public static int getFirstResult(int pageNumber, int pageSize) {
		if (pageSize < 0)
			throw new IllegalArgumentException("[pageSize] must great than zero");
		return pageNumber * pageSize;
	}

	public static List<Integer> generateLinkPageNumbers(int currentPageNumber, int lastPageNumber, int count) {
		int avg = count / 2;

		int startPageNumber = currentPageNumber - avg;
		if (startPageNumber <= 0) {
			startPageNumber = 1;
		}

		int endPageNumber = startPageNumber + count - 1;
		if (endPageNumber > lastPageNumber) {
			endPageNumber = lastPageNumber;
		}

		if (endPageNumber - startPageNumber < count) {
			startPageNumber = endPageNumber - count;
			if (startPageNumber <= 0) {
				startPageNumber = 1;
			}
		}

		List<Integer> result = new ArrayList<Integer>();
		for (int i = startPageNumber; i <= endPageNumber; i++) {
			result.add(new Integer(i));
		}
		return result;
	}

	public static int computeLastPageNumber(int totalElements, int pageSize) {
		int result = totalElements % pageSize == 0 ? totalElements / pageSize - 1 : totalElements / pageSize;
		if (result <= 0)
			result = 0;
		return result;
	}

	public static int computePageNumber(int pageNumber, int pageSize, int totalElements) {
		if (pageNumber <= 0) {
			return 0;
		}
		if (Integer.MAX_VALUE == pageNumber || pageNumber > computeLastPageNumber(totalElements, pageSize)) { // last
			                                                                                                  // page
			return computeLastPageNumber(totalElements, pageSize);
		}
		return pageNumber;
	}
}
